//思路：找规律，循环n/2次，奇数另外在遍历一下 [i+1,j]
//设置好四周边界条件防止越界,注意循环变量的变化;
class Solution {
    public static void main(String[] args) {
      int[][] nums=generateMatrix(4);
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j <nums[0].length ; j++) {
                System.out.print(nums[i][j]+" ");
            }
        }

    }

    //
    public  static int[][] generateMatrix(int n) {
       int[][] nums=new int[n][n];
       int k=1;
       int low=0,high=n-1;
       int left=0,right=n-1;
       while(left<=right&&low<=high){
           for ( int j = left; j <=right ; j++) {
               nums[low][j]=k++;
           }
           low++;
           for(int i = low; i <=high ; i++) {
               nums[i][right]=k++;
           }
           right--;
           if (low<=high) {
               for ( int j = right; j >=left ; j--) {
                   nums[high][j]=k++;
               }
           }
           high--;
           if (left<=right) {
               for(int i = high; i>=low ; i--) {
                   nums[i][left]=k++;
               }
           }
           left++;
       }
       return nums;
    }
}



